package com.tudonovelas;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class EvaluateActivity extends Activity {
	public static String avaliacao = ""; 
	public EditText texto;
	
	
	///////////////// COISAS DO FACEBOOK /////////////////
	///////////////// SE NAO SABE, NAO MEXA //////////////
	private static final String FACEBOOK_APPID = "566691080015318";
	private static final String FACEBOOK_PERMISSION = "publish_stream";
	private static final String TAG = "FacebookSample";
	
	private final Handler mFacebookHandler = new Handler();
	private FacebookConnector facebookConnector;
	///////////////// ATE AQUI ///////////////////////////
	//////////////////////////////////////////////////////

	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_evaluate);
		texto = (EditText) findViewById(R.id.texto);
		this.facebookConnector = new FacebookConnector(FACEBOOK_APPID, this, getApplicationContext(), new String[] {FACEBOOK_PERMISSION});

	}
	
	public void botaoClick(View view){
		avaliacao = texto.getText().toString();
		postMessage(avaliacao);
		Intent i = new Intent(getApplicationContext(), ListaNovelas.class);
		startActivity(i);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_evaluate, menu);
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		this.facebookConnector.getFacebook().authorizeCallback(requestCode, resultCode, data);
	}

	
	public void postMessage(final String msg) {

		if (facebookConnector.getFacebook().isSessionValid()) {
			postMessageInThread(msg);
		} else {
			SessionEvents.AuthListener listener = new SessionEvents.AuthListener() {				

				@Override
				public void onAuthSucceed() {
					postMessageInThread(msg);
				}

				@Override
				public void onAuthFail(String error) {

				}
			};
			SessionEvents.addAuthListener(listener);
			facebookConnector.login();
		}
	}
	
	final Runnable mUpdateFacebookNotification = new Runnable() {
        public void run() {
        	Toast.makeText(getBaseContext(), "Facebook updated !", Toast.LENGTH_LONG).show();
        }
    };
	
	private void postMessageInThread(final String msg) {
		Thread t = new Thread() {
			public void run() {

		    	try {
		    		facebookConnector.postMessageOnWall(msg);
					mFacebookHandler.post(mUpdateFacebookNotification);
				} catch (Exception ex) {
					Log.e(TAG, "Error sending msg",ex);
				}
		    }
		};
		t.start();
	}
}


